/*
 *  Copyright 2004 Blandware (http://www.blandware.com)
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package com.blandware.atleap.webapp.action.core.contentResource.file;

import com.blandware.atleap.common.Constants;
import com.blandware.atleap.model.core.ContentResource;
import com.blandware.atleap.model.core.ResourceData;
import com.blandware.atleap.service.core.ContentResourceManager;
import com.blandware.atleap.service.exception.BeanAlreadyExistsException;
import com.blandware.atleap.webapp.action.core.BaseAction;
import com.blandware.atleap.webapp.form.core.ContentResourceForm;
import com.blandware.atleap.webapp.form.core.UploadContentResourceForm;
import com.blandware.atleap.webapp.util.core.CacheUtil;
import com.blandware.atleap.webapp.util.core.ResourceTypesManager;
import com.blandware.atleap.webapp.util.core.WebappConstants;
import com.blandware.atleap.webapp.util.core.WebappUtil;
import org.apache.commons.validator.GenericValidator;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
import org.apache.struts.upload.FormFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * <p>Creates new content resource with type 'file'
 * </p>
 * <p><a href="CreateFileAction.java.html"><i>View Source</i></a></p>
 * <p/>
 *
 * @author Andrey Grebnev <a href="mailto:andrey.grebnev@blandware.com">&lt;andrey.grebnev@blandware.com&gt;</a>
 * @author Sergey Zubtsovskiy <a href="mailto:sergey.zubtsovskiy@blandware.com">&lt;sergey.zubtsovskiy@blandware.com&gt;</a>
 * @author Roman Puchkovskiy <a href="mailto:roman.puchkovskiy@blandware.com">
 *         &lt;roman.puchkovskiy@blandware.com&gt;</a>
 * @version $Revision: 1.24 $ $Date: 2008/04/29 17:48:07 $
 * @struts.action path="/core/contentResource/file/create"
 * name="contentResourceForm"
 * scope="request"
 * input="inputForward"
 * validate="true"
 * roles="core-contentResource-create"
 * @struts.action-forward name="inputForward"
 * path=".core.contentResource.file.create"
 * @struts.action-forward name="listContentResources"
 * path="/core/contentResource/list.do"
 * redirect="true"
 * @struts.action-forward name="createContentResource"
 * path=".core.contentResource.create"
 * @struts.action-forward name="closeWindow"
 * path=".core.contentResource.closeWindow"
 * @struts.action-forward name="unsatisfiable"
 * path="/core/contentResource/list.do"
 */
public final class CreateFileAction extends BaseAction {
	/**
	 * @param mapping  The ActionMapping used to select this instance
	 * @param form     The optional ActionForm bean for this request (if any)
	 * @param request  The HTTP request we are proceeding
	 * @param response The HTTP response we are creating
	 * @return an ActionForward instance describing where and how
	 *         control should be forwarded, or null if response
	 *         has already been completed
	 */
	public ActionForward execute(ActionMapping mapping, ActionForm form,
	                             HttpServletRequest request, HttpServletResponse response) throws Exception {

		ContentResourceForm contentResourceForm = (ContentResourceForm) form;
        HttpSession session = request.getSession();
        boolean closeWindowAfterCreated = Boolean.TRUE.equals(session.getAttribute(WebappConstants.CONTENT_RESOURCE_CLOSE_WINDOW_AFTER_CREATED_KEY));

        String requestUrl = (String) session.getAttribute(WebappConstants.REDIRECT_URL_KEY);
        
        UploadContentResourceForm uploadContentResourceForm = (UploadContentResourceForm) session
                .getAttribute(WebappConstants.UPLOAD_CONTENT_RESOURCE_FORM_KEY);
		if ( uploadContentResourceForm == null || uploadContentResourceForm.getFile() == null ) {
            // Maybe session was invalidated and after that user pressed 'back'
            // or 'cancel'?
            if (isBackPressed(request)) {
                session.removeAttribute(WebappConstants.UPLOAD_CONTENT_RESOURCE_FORM_KEY);
                saveToken(request);
                return mapping.findForward("createContentResource");
            }
            if ( isCancelled(request) ) {
                session.removeAttribute(WebappConstants.UPLOAD_CONTENT_RESOURCE_FORM_KEY);
                session.removeAttribute(WebappConstants.CONTENT_RESOURCES_FOLDER_KEY);
                session.removeAttribute(WebappConstants.CONTENT_RESOURCE_TYPE_KEY);
                session.removeAttribute(WebappConstants.CONTENT_RESOURCE_CLOSE_WINDOW_AFTER_CREATED_KEY);
                if (closeWindowAfterCreated) {
                    request.setAttribute("createdContentResource", Boolean.FALSE);
                    return mapping.findForward("closeWindow");
                }
                if ( !GenericValidator.isBlankOrNull(requestUrl) ) {
                    session.removeAttribute(WebappConstants.REDIRECT_URL_KEY);
                    return new ActionForward(requestUrl, true);
                }
                return mapping.findForward("listContentResources");
            }
			if ( log.isWarnEnabled() ) {
				log.warn("Missing required attribute in session '" + WebappConstants.UPLOAD_CONTENT_RESOURCE_FORM_KEY + "'");
			}
			ActionMessages errors = new ActionMessages();
			errors.add("missingResource", new ActionMessage("core.contentResource.errors.missingResource"));
			saveErrors(request, errors);
			saveToken(request);
			return mapping.getInputForward();
		}
		FormFile formFile = uploadContentResourceForm.getFile();
		String fileName = formFile.getFileName();

        if (isBackPressed(request)) {
			if ( formFile != null ) {
				formFile.destroy();
			}
			session.removeAttribute(WebappConstants.UPLOAD_CONTENT_RESOURCE_FORM_KEY);
			saveToken(request);
			return mapping.findForward("createContentResource");
		}

		if ( isCancelled(request) ) {
			if ( formFile != null ) {
				formFile.destroy();
			}
			session.removeAttribute(WebappConstants.UPLOAD_CONTENT_RESOURCE_FORM_KEY);
            session.removeAttribute(WebappConstants.CONTENT_RESOURCES_FOLDER_KEY);
            session.removeAttribute(WebappConstants.CONTENT_RESOURCE_TYPE_KEY);
            session.removeAttribute(WebappConstants.CONTENT_RESOURCE_CLOSE_WINDOW_AFTER_CREATED_KEY);
            if (closeWindowAfterCreated) {
                request.setAttribute("createdContentResource", Boolean.FALSE);
                return mapping.findForward("closeWindow");
            }
            if ( !GenericValidator.isBlankOrNull(requestUrl) ) {
                session.removeAttribute(WebappConstants.REDIRECT_URL_KEY);
                return new ActionForward(requestUrl, true);
            }
            return mapping.findForward("listContentResources");
		}

		ResourceTypesManager resourceTypesManager = ResourceTypesManager.getInstance(
                session.getServletContext());

		if ( log.isDebugEnabled() ) {
			log.debug("Storing formFile '" + fileName + "' into DB");
		}

		ContentResource file = new ContentResource();
		WebappUtil.copyProperties(file, contentResourceForm, request);
        WebappUtil.copyFieldValue(file.getDescription(), contentResourceForm.getDescriptionMap());

        //setup uri
		String uri = Constants.RESOURCES_URI_PREFIX + contentResourceForm.getUri();
		file.setUri(uri);

		file.setType(Constants.RESOURCE_TYPE_FILE);
		String mimeType = resourceTypesManager.getMimeTypeByFileName(fileName);
		file.setMimeType(mimeType);

		byte[] fileData = formFile.getFileData();

		file.setSize(new Long(fileData.length));

		ContentResourceManager contentResourceManager = (ContentResourceManager) getBean(Constants.CONTENT_RESOURCE_MANAGER_BEAN);
		try {
			Long contentResourceId = contentResourceManager.createContentResource(file, new ResourceData(fileData));

			//put into cache
			file = contentResourceManager.retrieveContentResource(contentResourceId);
			CacheUtil cacheUtil = CacheUtil.getInstance(request);
			CacheUtil.ResourceData rd = new CacheUtil.ResourceData(fileData, mimeType, null, file.getLastUpdatedDatetime().getTime());
			cacheUtil.putResourceInCache(rd, uri);

		} catch ( BeanAlreadyExistsException e ) {
			// content resource already exists
			ActionMessages errors = new ActionMessages();
			errors.add("contentResourceAlreadyExists", new ActionMessage("core.contentResource.errors.alreadyExists"));
			saveErrors(request, errors);
			saveToken(request);
			return mapping.getInputForward();
		}
		if ( formFile != null ) {
			formFile.destroy();
		}
		session.removeAttribute(WebappConstants.UPLOAD_CONTENT_RESOURCE_FORM_KEY);
        session.removeAttribute(WebappConstants.CONTENT_RESOURCES_FOLDER_KEY);
        session.removeAttribute(WebappConstants.CONTENT_RESOURCE_TYPE_KEY);
        session.removeAttribute(WebappConstants.CONTENT_RESOURCE_CLOSE_WINDOW_AFTER_CREATED_KEY);

        if (closeWindowAfterCreated) {
            request.setAttribute("createdContentResource", Boolean.TRUE);
            request.setAttribute("createdContentResourceUri", file.getUri());
            return mapping.findForward("closeWindow");
        }
        if ( !GenericValidator.isBlankOrNull(requestUrl) ) {
            session.removeAttribute(WebappConstants.REDIRECT_URL_KEY);
            return new ActionForward(requestUrl, true);
        }
        return mapping.findForward("listContentResources");

	}
}